package com.cpd.blog.manager.manager.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cpd.blog.entity.ArticleTag;
import com.cpd.blog.entity.Tag;
import com.cpd.blog.manager.manager.TagManager;
import com.cpd.blog.manager.mapper.ArticleTagMapper;
import com.cpd.blog.manager.mapper.TagMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.LinkedList;
import java.util.List;

/**
 * @Author: Copydown
 * @Date: 2022/05/01/1:12
 */
@Service
@RequiredArgsConstructor
public class TagManagerImpl implements TagManager {

    private final ArticleTagMapper articleTagMapper;

    private final TagMapper tagMapper;

    @Override
    public List<Tag> findHotsTagIds(int limit) {

        LambdaQueryWrapper<ArticleTag> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.
                select(ArticleTag::getTagId)
                .groupBy(ArticleTag::getTagId)
                .last("order by count(*) desc limit " + limit);

        List<ArticleTag> articleTagList = articleTagMapper.selectList(queryWrapper);

        if (articleTagList.size() == 0) {
            return null;
        }

        List<Tag> tags = new LinkedList<>();
        LambdaQueryWrapper<Tag> tagQueryWrapper = new LambdaQueryWrapper<>();
        for (ArticleTag articleTag : articleTagList) {
            tagQueryWrapper.eq(Tag::getId, articleTag.getTagId());
            tags.add(tagMapper.selectOne(tagQueryWrapper));
            tagQueryWrapper.clear();
        }

        return tags;
    }
}
